package cn.tedu.zx.sso.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * admin管理员的数据源相关信息配置
 */
@Configuration
//basePackages = "cn.tedu.zx.sso.mapper.admin"扫描一下路径的包
//sqlSessionTemplateRef = "db1SqlSessionTemplate"指定了要使用的SqlSessionTemplate的Bean名称
@MapperScan(basePackages = "cn.tedu.zx.sso.mapper.admin",sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DataSource1Configuration {
    /**
     * 生产默认数据源
     */
    @Bean(name = "db1DataSource")
    //添加bean名前缀
    @ConfigurationProperties(prefix = "spring.datasource.admin")
    //优先加载此bean
    @Primary
    public DataSource testDataSource(){
        return DataSourceBuilder.create().build();
    }


    @Bean(name="db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(
            @Qualifier("db1DataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources
                ("classpath:mapper/admin/*.xml"));
        return bean.getObject();
    }

    /**
     * 配置事务管理
     */
    @Bean(name="db1TransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(
            @Qualifier("db1DataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
